<template>
  <div class="bg-light">
    <!-- 头部 -->
    <div class="header d-flex align-items-center">
      <router-link :to="`/english/exam?year=${selectedYear}`" @click.prevent="submitAnswers" class="text-dark">
        <i class="bi bi-chevron-left fs-4"></i>
      </router-link>
      <h5 class="mb-0 mx-auto">{{ selectedYear }} 阅读 Text {{ textNumber }}</h5>
      <i class="bi bi-bookmark text-muted"></i>
    </div>

    <!-- 阅读工具栏 -->
    <div class="reading-tools d-flex justify-content-around">
      <button class="tool-btn" id="translateBtn" @click="toggleTranslation">
        <i class="bi bi-translate"></i> 全文翻译
      </button>
      <button class="tool-btn" id="difficultBtn" @click="toggleDifficult">
        <i class="bi bi-braces"></i> 长难句解析
      </button>
      <button class="tool-btn" id="vocabBtn" @click="toggleVocab">
        <i class="bi bi-book"></i> 生词本
      </button>
    </div>

    <!-- 阅读内容 -->
    <div class="reading-content" v-if="readingData.readingContent">
      <div v-for="(paragraph, index) in readingData.readingContent" :key="index" class="paragraph" :data-paragraph-id="index">
        <span class="paragraph-number">[{{ index + 1 }}]</span>
        <div class="english-text">
                    <span v-for="word in paragraph.englishText" class="clickable-word"
                          :class="{ 'new-word': word.newWord }"
                          :data-word="word.word"
                          :data-phonetic="word.phonetic"
                          :data-meaning="word.meaning">{{ word.word }}</span>
        </div>
        <div class="chinese-text">{{ paragraph.chineseText }}</div>
<!--        <div v-for="sentence in paragraph.sentenceAnalysis" class="sentence-analysis"-->
<!--             :id="'analysis-' + sentence.id">-->
<!--          <div class="analysis-title">长难句解析</div>-->
<!--          <div class="analysis-content">-->
<!--            <div class="structure-analysis">-->
<!--              <p><strong>句子结构：</strong></p>-->
<!--              <p>主干：{{ sentence.structure.main }}</p>-->
<!--              <p>并列谓语：</p>-->
<!--              <ul>-->
<!--                <li v-for="predicate in sentence.structure.predicates">{{ predicate }}</li>-->
<!--              </ul>-->
<!--              <p>目的状语：{{ sentence.structure.purpose }}</p>-->
<!--            </div>-->
<!--            <div class="translation-result">-->
<!--              <p><strong>译文：</strong></p>-->
<!--              <p>{{ sentence.translation }}</p>-->
<!--            </div>-->
<!--          </div>-->
<!--        </div>-->
        <div class="sentence-analysis" :id="'analysis-' + index">
          <!-- 解析内容会动态插入到这里 -->
        </div>
      </div>
    </div>

    <!-- 题目部分 -->
    <div class="question-section" v-if="readingData.questions">
      <div v-for="(question, questionIndex) in readingData.questions" :key="questionIndex" class="question">
        <p><strong>{{ question.qtitle }}</strong></p>
        <div v-for="(option, optionIndex) in question.item" :key="option.prefix"  class="option-item"
           @click.prevent="selectAnswer(questionIndex, optionIndex,option.prefix)">
          {{ option.prefix }}. {{ option.content }}
        </div>
      </div>
    </div>

    <!-- 底部工具栏 -->
    <div class="bottom-tools">
      <div>
        <button class="btn btn-outline-primary btn-sm me-2"
                @click="prevQuestion"
                :disabled="textNumber === 1">上一篇</button>
        <button class="btn btn-outline-primary btn-sm"
                @click="nextQuestion"
                :disabled="textNumber === totalQuestions">下一篇</button>
      </div>
      <div>
        <button class="btn btn-primary" @click="goToAnalysis">答案解析</button>
      </div>
    </div>
  </div>
</template>

<script>
import http from "@/router/http";
import {paperTypeDict, moduleTypeDict} from "@/router/dict"
import router from "@/router";
import {getTranslationInfo, getTranslationParaGraphInfo,getTranslationArticleInfo} from '@/services/BaiduTranslationService';

export default {
  name: 'EnglishReadingTextView',
  data() {
    return {
      examPaperId: null,
      articleId: null,
      totalQuestions: 4, // 总题目数
      selectedYear: null,
      textNumber: null, // 阅读内容
      readingData: {}, // 用于存储从后端获取的整个阅读相关数据
      isLoading: true, // 表示数据是否正在加载的状态，初始为 true
      selectedAnswers: {}, // 用于存储用户选择的答案，以题目编号为键，答案值为值
      userAnswers: [],
      wordTooltip: null,
      analysisData: [],
      vocabList: [],
      // 生词本列表
      currentWord: {
        word: '',
        phonetic: '',
        meaning: '',
        isNewWord: false,
        collected: false
      },
      showVocab: false, // 添加这个来跟踪生词本模式状态
      startTime: 0, // 记录答题开始时间（毫秒数）
      totalTimeSpent: 0, // 累计答题时间（毫秒数）
      isWordClickProcessing: false,
      prevQuestionEventBound: false, // 标记上一题切换时是否已绑定事件
      nextQuestionEventBound: false, // 标记下一题切换时是否已绑定事件
      clickEventsBound: false,
    }
  },
  beforeRouteEnter(to, from, next) {
    // 在进入路由前，将组件实例的属性设置为false，表示未绑定点击事件
    to.meta.wordClickEventBound = false;
    next();
  },
  beforeRouteLeave(to, from, next) {
    // 在离开当前路由时，获取当前组件实例（通过vm参数），并移除已经绑定的点击事件（如果有）
    const vm = this;
    const removeClickEvent = function () {
      document.removeEventListener('click', vm.handleWordClickWrapper);
    };
    removeClickEvent();
    next();
  },
  created() {
    this.selectedYear = this.$route.query.year;
    this.textNumber = this.$route.query.text;
    this.startTime = Date.now();
  },
  methods: {
    toggleTranslation() {
      const btn = document.getElementById('translateBtn');
      const wasActive = btn.classList.contains('active'); // 记录按钮点击前的状态
      btn.classList.toggle('active');
      const paragraphs = document.querySelectorAll('.paragraph');

      if (btn.classList.contains('active')) {
        // 展开全文翻译时，遍历段落进行翻译请求
        paragraphs.forEach((paragraph, index) => {
          const englishText = paragraph.querySelector('.english-text').textContent;
          const cleanEnglishText = englishText.replace(/[^\w\s]/g, '').replace(/&quot;/g, '');

          getTranslationParaGraphInfo(cleanEnglishText, index,this.articleId)
              .then(response => {
                const chineseText = response.meaning;
                const chineseTextDiv = paragraph.querySelector('.chinese-text');
                if (chineseTextDiv) {
                  chineseTextDiv.textContent = chineseText;
                  chineseTextDiv.style.display = 'block';
                  setTimeout(() => chineseTextDiv.classList.add('show'), 10);
                }
              })
              .catch(error => {
                console.error('获取段落翻译出错:', error);
              });
        });
      } else {
        // 收起全文翻译时，仅处理样式隐藏，不进行接口调用
        paragraphs.forEach(paragraph => {
          const chineseTextDiv = paragraph.querySelector('.chinese-text');
          if (chineseTextDiv) {
            chineseTextDiv.classList.remove('show');
            setTimeout(() => chineseTextDiv.style.display = 'none', 300);
          }
        });
      }
    },
    // toggleDifficult() {
    //   const btn = document.getElementById('difficultBtn')
    //   btn.classList.toggle('active')
    //   document.querySelectorAll('.difficult-sentence').forEach(el => {
    //     el.classList.toggle('highlight')
    //   })
    //   if (!btn.classList.contains('active')) {
    //     document.querySelectorAll('.sentence-analysis').forEach(el => {
    //       el.classList.remove('show')
    //     })
    //   }
    // },
     async toggleDifficult() {
      const btn = document.getElementById('difficultBtn');
      btn.classList.toggle('active');

      if (btn.classList.contains('active')) {
        const paragraphs = document.querySelectorAll('.paragraph');
        paragraphs.forEach( (paragraph,index) => {
          // 获取当前段落的英文文本内容
          const paragraphText = this.analysisData[index];
          const textInfo = {
            text: paragraphText.replace(/"/g, '\\"').replace(/\n/g, '\\n').replace("£",""),
          }
          // 向AI接口发送当前段落的文本进行长难句分析，注意这里根据实际情况调整请求参数
           http.post('/student/ai/english/long_sentence_analyze', {
             text: JSON.stringify(textInfo),
             questionId: this.readingData.questionId,
             paragraph: index
          },{
              headers: {
                  'Content-Type': 'application/json; charset=UTF-8'
              }
           }).then(response => {
            if (response.data.code === 1) {
              const analysisData = response.data.response;
              // 获取当前段落对应的解析结果展示元素
              const analysisDiv = document.getElementById('analysis-'+index);
              if (analysisDiv) {
                // 清空之前可能存在的解析内容（避免多次点击重复添加）
                analysisDiv.innerHTML = '';

                // 在这里遍历分析数据，将每个解析项展示到对应的段落解析结果元素中
                // 示例中假设分析数据是一个对象，对象的每个属性是一种解析内容（比如句子结构、译文等）
                // 你需要根据实际返回的数据结构进行调整
                Object.entries(analysisData).forEach(([key, value]) => {
                  const sectionDiv = document.createElement('div');
                  sectionDiv.classList.add('analysis-section');

                  const titleP = document.createElement('p');
                  titleP.innerHTML = `<strong>${key}</strong>`;

                  const valueDiv = document.createElement('div');
                  valueDiv.classList.add('analysis-value');
                  valueDiv.innerHTML = this.renderJsonValue(value);

                  sectionDiv.appendChild(titleP);
                  sectionDiv.appendChild(valueDiv);
                  analysisDiv.appendChild(sectionDiv);
                });
                paragraph.classList.add('highlight');
                analysisDiv.style.display = 'block';
                setTimeout(() => analysisDiv.classList.add('show'), 10);
              }
            }
          }).catch(error => {
            console.error('Analysis request failed for paragraph:', paragraphText, error);
          });
        });
      } else {
        // 移除所有段落中的长难句高亮显示，保持单词的可点击性
        document.querySelectorAll('.difficult-sentence').forEach((el) => {
          const wordSpans = Array.from(el.querySelectorAll('.clickable-word'));
          const fragment = document.createDocumentFragment();

          wordSpans.forEach((span, index) => {
            fragment.appendChild(span);
            if (index < wordSpans.length - 1) {
              fragment.appendChild(document.createTextNode(' '));
            }
          });

          el.parentNode.insertBefore(fragment, el);
          el.remove();
        });

        // 隐藏所有段落中的长难句解析结果展示元素
        document.querySelectorAll('.sentence-analysis').forEach((el) => {
          el.classList.remove('show');
          setTimeout(() => el.style.display = 'none', 300);
        });
      }
    },
    toggleVocab() {
      const btn = document.getElementById('vocabBtn')
      btn.classList.toggle('active')
      this.showVocab = !this.showVocab // 添加这行来跟踪生词本模式状态
      document.querySelectorAll('.new-word').forEach(el => {
        el.classList.toggle('highlight')
      })
    },
    selectAnswer(questionIndex, optionIndex,optionPrefix) {
      const questions = document.querySelectorAll('.question');
      const currentQuestion = questions[questionIndex];
      const options = currentQuestion.querySelectorAll('.option-item');
      options.forEach(opt => {
        opt.classList.remove('selected');
      });
      const selectedOption = options[optionIndex];
      if (selectedOption) {
        selectedOption.classList.add('selected');
      }
      this.selectedAnswers[questionIndex] = optionIndex;
      const existingIndex = this.userAnswers.findIndex(item => item.index === questionIndex);
      if(existingIndex > -1){
        this.userAnswers[existingIndex].value = optionPrefix;
      }else{
        this.userAnswers.push({
          index: questionIndex,
          value: optionPrefix
        })
      }
    },
    goToAnalysis() {
      // this.submitAnswers();
      // 构建需要传递的参数
      const queryParams = {
        year: this.selectedYear,
        subjectName: 'english',
        paperType: paperTypeDict.find(item => item.label === '历年真题').value,
        moduleType: moduleTypeDict.find(item => item.code === 'ydlj').name,
        currentQuestionIndex: this.textNumber,
        part: `text${this.textNumber}`
      };
      
      // 使用路由导航并传递参数
      this.$router.push({
        name: 'EnglishReadingAnalysis',
        query: queryParams
      });
    },
    addToVocab(wordData) {
      const exists = this.vocabList.some(item => item === wordData.word)
      if (!exists) {
        this.vocabList.push(wordData.word)
      }
    },
    removeFromVocab(word) {
      this.vocabList = this.vocabList.filter(item => item !== word)
    },
    handleWordClick(event, word) {
      if (this.isWordClickProcessing) {
        return; // 如果正在处理单词点击，直接返回，不再执行后续逻辑
      }
      this.isWordClickProcessing = true;
      let wordData = {}
      // if (word.classList.contains('new-word')) {
      //   // 处理预设的生词
      //   wordData = {
      //     word: word.dataset.word,
      //     phonetic: word.dataset.phonetic,
      //     meaning: word.dataset.meaning
      //   }
      //   this.showWordTooltip(wordData, event)
      // } else {
        // 处理普通单词
        const wordText = word.textContent.trim().toLowerCase()
            .replace(/[.,!?;:"']/g, '').replaceAll("[\\p{Punct}]+", "") // 移除标点符号
      const punctuationRegex = /[!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~"]+/g;
      const wordText2 = wordText.replace(punctuationRegex, '').replace('”','').replace('“','') // 移除所有标点符号
        wordData = {
          word: wordText2,
          phonetic: '', // 将通过API获取
          meaning: '',   // 将通过API获取,
          audio: '', // 读音
          example: '', // 例句
          exampleCn: '' // 例句
        }
        this.fetchWordTranslation(wordData, event)
      // }
      this.isWordClickProcessing = false;
    },
    renderJsonValue(value) {
      if (value === null) return 'null';
      if (typeof value === 'undefined') return 'undefined';
      if (typeof value !== 'object') return value;

      return Object.entries(value).map(([key, val]) => `
          <div class="json-item">
            <span class="json-key">${key}:</span>
            <div class="json-value">
              ${Array.isArray(val)
          ? `<div class="json-array">
                    ${val.map(item =>
              `<div class="json-array-item">
                        ${typeof item === 'object' ? this.renderJsonValue(item) : item}
                      </div>`
          ).join('')}
                  </div>`
          : typeof val === 'object' && val !== null
              ? this.renderJsonValue(val)
              : `<span class="json-primitive">${val}</span>`
      }
            </div>
          </div>
        `).join('');
    },
    showWordTooltip(wordData, event) {
      if (!this.wordTooltip) {
        this.wordTooltip = document.createElement('div')
        this.wordTooltip.className = 'word-tooltip'
        document.body.appendChild(this.wordTooltip)
      }
      const isCollected = this.vocabList.some(item => item === wordData.word)
      this.wordTooltip.innerHTML = `
          <div class="tooltip-header">
            <strong>${wordData.word}</strong>
            <button class="collect-word-btn ${isCollected ? 'collected' : ''}"
                    data-word='${JSON.stringify(wordData)}'>
              ${isCollected ? '已添加' : '添加生词'}
            </button>
          </div>
          ${wordData.phonetic ? `<div>${wordData.phonetic}</div>` : '<div class="loading-phonetic">获取音标中...</div>'}
          ${wordData.meaning ? `<div>${wordData.meaning}</div>` : '<div class="loading-meaning">获取释义中...</div>'}
        `

      const rect = event.target.getBoundingClientRect()
      this.wordTooltip.style.top = `${rect.bottom + window.scrollY + 5}px`
      this.wordTooltip.style.left = `${rect.left}px`
      this.wordTooltip.style.display = 'block'
      this.wordTooltip.classList.add('show')

      // 为收藏按钮添加点击事件
      const collectBtn = this.wordTooltip.querySelector('.collect-word-btn')
      collectBtn.addEventListener('click', (e) => {
        const btnWordData = JSON.parse(e.target.dataset.word)
        const exists = this.vocabList.some(item => item === btnWordData.word)
        let type;
        if (exists) {
          type = 0
          this.removeFromVocab(btnWordData.word)
        } else {
          type = 1;
          this.addToVocab(btnWordData)
        }

        e.target.classList.toggle('collected')
        e.target.textContent = exists ? '添加生词' : '已添加'
        const exampleInfo = [];
        if(btnWordData.example && btnWordData.exampleCn){
          exampleInfo.push(btnWordData.example,btnWordData.exampleCn)
        }
        const response =  http.post('/student/vocabularyList/addOrDelete?type='+type, {
          questionId: this.readingData.questionId,
          newWord: btnWordData.word,
          phoneticSymbol: btnWordData.phonetic,
          translate: btnWordData.meaning,
          audio: btnWordData.audio,
          sentenceTranslate: exampleInfo
        })
      })
    },
    async fetchWordTranslation(wordData, event) {
      try {
        const data = await getTranslationInfo(wordData.word);
        wordData.phonetic = data.pronunciationStr || ''
        wordData.meaning = data.meaning || '未找到释义'
        wordData.audio = data.audio || ''
        wordData.example = data.example || ''
        let exampleCn = ''
        if(data.example !== ''){
           exampleCn = (await getTranslationArticleInfo(data.example)).meaning || ''
        }
        wordData.exampleCn = exampleCn || ''
        // 更新tooltip内容
        this.showWordTooltip(wordData, event)
      } catch (error) {
        console.error('获取翻译失败:', error)
        wordData.meaning = '获取释义失败'
        this.showWordTooltip(wordData, event)
      }
    },
    // 将文本内容拆分成可点击的单词
    wrapWordsWithSpan(text) {
      // 使用正则表达式匹配单词，保留标点符号
      return text.replace(/([a-zA-Z]+[-'']?[a-zA-Z]*)/g, '<span class="clickable-word">$1</span>')
    },
    async fetchReadingData() {
      try {
        const paperType = paperTypeDict.find(item => item.label === '历年真题').value;
        const moduleType = moduleTypeDict.find(item => item.code === 'ydlj').name;
        const params = {
          year: this.selectedYear,
          subjectName: 'english',
          paperType: paperType,
          moduleType: moduleType,
          currentQuestionIndex: this.textNumber
        }
        this.readingData = {}
        const response = await http.get('/student/question/getQuestionInfoForEnglish', {params: params}); // 假设后端获取阅读数据的接口地址，需根据实际情况修改
        const data = response.data
        if (!data || !data.response) {
          console.error('获取阅读数据失败:', data.message);
          alert("暂无数据，请稍后再试");
          router.push("/english/exam?year="+this.selectedYear)
          this.isLoading = false;
          return;
        }
        this.readingData = data.response;
        this.textNumber = data.response.currentQuestionIndex;
        this.examPaperId = data.response.examPaperId;
        this.articleId = data.response.articleId;
        this.vocabList = data.response.vocabList || [];
        this.analysisData = data.response.nalysisTextList || [];
        this.isLoading = false;
        await this.buildStyle();
        // 重置事件绑定相关标志位
        // this.prevQuestionEventBound = false;
        // this.nextQuestionEventBound = false;
        // this.clickEventsBound = false;
      } catch (error) {
        console.error('获取阅读数据失败:', error);
        this.isLoading = false;
      }
    },
    async buildStyle() {
      // 从本地存储加载生词本
      // const savedVocabList = localStorage.getItem('vocabList')
      // if (savedVocabList) {
      //   this.vocabList = JSON.parse(savedVocabList)
      // }
      // 点击页面其他地方关闭 tooltip
      if (!this.clickEventsBound) {
        document.addEventListener('click', (e) => {
          if (this.wordTooltip && !e.target.closest('.word-tooltip') && !e.target.closest('.new-word')) {
            this.wordTooltip.style.display = 'none'
            this.wordTooltip.classList.remove('show')
          }
        })
        // 处理所有英文文本内容
        document.querySelectorAll('.english-text').forEach(element => {
          // 跳过已经处理过的 new-word 元素和 difficult-sentence 元素
          const textNodes = Array.from(element.childNodes).filter(node =>
              (node.nodeType === Node.TEXT_NODE ||
                  (node.nodeType === Node.ELEMENT_NODE &&
                      !node.classList.contains('new-word') &&
                      !node.classList.contains('difficult-sentence')))
          )

          textNodes.forEach(node => {
            if (node.nodeType === Node.TEXT_NODE) {
              const span = document.createElement('span')
              span.innerHTML = this.wrapWordsWithSpan(node.textContent)
              node.parentNode.replaceChild(span, node)
            }
          })
        })
        // 修改点击事件监听器
        document.addEventListener('click', (e) => {
          // 处理单词点击
          // const wordElement = e.target.closest('.clickable-word, .new-word')
          // if (wordElement) {
          //   e.preventDefault()
          //   e.stopPropagation()
          //   this.handleWordClick(e, wordElement)
          //   return
          // }

          // 处理长难句点击
          const sentence = e.target.closest('.difficult-sentence')
          if (sentence && document.getElementById('difficultBtn').classList.contains('active')) {
            const sentenceId = sentence.dataset.sentenceId
            const analysis = document.getElementById(`analysis-${sentenceId}`)

            if (analysis.classList.contains('show')) {
              analysis.classList.remove('show')
              setTimeout(() => analysis.style.display = 'none', 300)
            } else {
              document.querySelectorAll('.sentence-analysis').forEach(el => {
                el.classList.remove('show')
                el.style.display = 'none'
              })
              analysis.style.display = 'block'
              setTimeout(() => analysis.classList.add('show'), 10)
            }
          }
        });
        this.clickEventsBound = true;
      }
    },
    prevQuestion() {
      if (this.textNumber > 1) {
        this.submitAnswers();
        this.textNumber--;
        this.userAnswers = []
        this.selectedAnswers = {}
        this.fetchReadingData().then(() => {
          if (!this.prevQuestionEventBound) {
            const questions = document.querySelectorAll('.question');
            questions.forEach((question, index) => {
              const selectedOptionIndex = this.selectedAnswers[index];
              if (selectedOptionIndex !== undefined) {
                const options = question.querySelectorAll('.option');
                const optionElement = options[selectedOptionIndex];
                if (optionElement) {
                  optionElement.classList.add('selected');
                }
              }
            });
            this.prevQuestionEventBound = true;
          }
          // 重置全文翻译按钮状态及相关显示效果
          const translateBtn = document.getElementById('translateBtn');
          if (translateBtn.classList.contains('active')) {
            translateBtn.classList.remove('active');
            const paragraphs = document.querySelectorAll('.paragraph');
            paragraphs.forEach(paragraph => {
              const chineseTextDiv = paragraph.querySelector('.chinese-text');
              if (chineseTextDiv) {
                chineseTextDiv.classList.remove('show');
                setTimeout(() => chineseTextDiv.style.display = 'none', 300);
              }
            });
          }

          // 重置长难句解析按钮状态及相关显示效果
          const difficultBtn = document.getElementById('difficultBtn');
          if (difficultBtn.classList.contains('active')) {
            difficultBtn.classList.remove('active');
            document.querySelectorAll('.difficult-sentence').forEach(el => {
              el.classList.remove('highlight');
            });
            document.querySelectorAll('.sentence-analysis').forEach(el => {
              el.classList.remove('show');
              setTimeout(() => el.style.display = 'none', 300);
            });
          }

          // 重置生词本按钮状态及相关显示效果
          const vocabBtn = document.getElementById('vocabBtn');
          if (vocabBtn.classList.contains('active')) {
            vocabBtn.classList.remove('active');
            document.querySelectorAll('.new-word').forEach(el => {
              el.classList.remove('highlight');
            });
          }
        });
      }
    },
    nextQuestion() {
      if (this.textNumber < this.totalQuestions) {
        this.submitAnswers();
        this.textNumber++;
        this.userAnswers = []
        this.selectedAnswers = {}
        this.fetchReadingData().then(() => {
          if (!this.nextQuestionEventBound) {
            const questions = document.querySelectorAll('.question');
            questions.forEach((question, index) => {
              const selectedOptionIndex = this.selectedAnswers[index];
              if (selectedOptionIndex !== undefined) {
                const options = question.querySelectorAll('.option');
                const optionElement = options[selectedOptionIndex];
                if (optionElement) {
                  optionElement.classList.add('selected');
                }
              }
            });
            this.nextQuestionEventBound = true;
          }
          // 重置全文翻译按钮状态及相关显示效果
          const translateBtn = document.getElementById('translateBtn');
          if (translateBtn.classList.contains('active')) {
            translateBtn.classList.remove('active');
            const paragraphs = document.querySelectorAll('.paragraph');
            paragraphs.forEach(paragraph => {
              const chineseTextDiv = paragraph.querySelector('.chinese-text');
              if (chineseTextDiv) {
                chineseTextDiv.classList.remove('show');
                setTimeout(() => chineseTextDiv.style.display = 'none', 300);
              }
            });
          }

          // 重置长难句解析按钮状态及相关显示效果
          const difficultBtn = document.getElementById('difficultBtn');
          if (difficultBtn.classList.contains('active')) {
            difficultBtn.classList.remove('active');
            document.querySelectorAll('.difficult-sentence').forEach(el => {
              el.classList.remove('highlight');
            });
            document.querySelectorAll('.sentence-analysis').forEach(el => {
              el.classList.remove('show');
              setTimeout(() => el.style.display = 'none', 300);
            });
          }

          // 重置生词本按钮状态及相关显示效果
          const vocabBtn = document.getElementById('vocabBtn');
          if (vocabBtn.classList.contains('active')) {
            vocabBtn.classList.remove('active');
            document.querySelectorAll('.new-word').forEach(el => {
              el.classList.remove('highlight');
            });
          }
        });
      }
    },
    async submitAnswers() {
      try {
        const currentTime = Date.now(); // 获取当前时间（毫秒数）
        this.totalTimeSpent += currentTime - this.startTime; // 累计答题时间
        const submitParentData = {
          questionId: this.readingData.questionId,
          examPaperId: this.examPaperId,
          totalTimeSpent: this.totalTimeSpent,
          resource: 1,
          userAnswer: this.userAnswers
        }

        // 发送POST请求将答题数据提交到后端
        const response = await http.post('/student/answer/submitAnswerForEnglish', submitParentData);
        if (response.status === 200) {
          console.log('答题数据提交成功');
          // router.push('/english/exam?year='+this.selectedYear);
          // 可以根据业务需求进行其他操作，比如提示用户提交成功，跳转到特定页面等
        } else {
          console.error('答题数据提交失败');
          // router.push('/english/exam?year='+this.selectedYear);
          // 同样可根据业务需求进行相应提示等操作
        }
      } catch (error) {
        console.error('提交答题数据出现错误:', error);
      }
    },
  },
  mounted() {
    this.fetchReadingData();
    const vm = this;
    if (!this.$route.meta.wordClickEventBound) {
      // 创建一个包装函数，用于在内部调用真正的handleWordClick方法，并处理this指向问题
      const handleWordClickWrapper = function (e) {
        const wordElement = e.target.closest('.clickable-word,.new-word');
        if (wordElement) {
          e.preventDefault();
          e.stopPropagation();
          vm.handleWordClick(e, wordElement);
          return;
        }
      };
      document.addEventListener('click', handleWordClickWrapper);
      this.$route.meta.wordClickEventBound = true; // 绑定成功后，在路由元信息中标记为已绑定
      this.handleWordClickWrapper = handleWordClickWrapper; // 保存包装函数的引用，方便后续移除
    }

  },
  beforeDestroy() {
    // 清理工作
    if (this.wordTooltip && this.wordTooltip.parentNode) {
      this.wordTooltip.parentNode.removeChild(this.wordTooltip)
    }
  },
}
</script>

<style>
.translation-error {
  text-align: center;
  padding: 10px;
  color: #ff4444;
}
.option-item {
  background: white;
  padding: 15px;
  margin-bottom: 10px;
  border-radius: 10px;
  cursor: pointer;
}

.option-item.selected {
  background: #40e0d0;
  color: white;
}
.clickable-word {
  margin-right: 4px; /* 根据实际需要调整间距值，这里设置为10px，可自行更改 */
  /* 或者使用 padding 属性来增加间距，例如： */
  /* padding: 0 5px; */
}
.new-word {
  margin-right: 10px;
  /* 同样也可以添加 padding 属性，如：padding: 0 5px; */
}
.english-text {
  word-spacing: 8px; /* 设置单词间距为8px，可按需修改 */
}
body {
  background-color: #f0f9f9;
}

.header {
  padding: 15px;
  background: white;
  position: sticky;
  top: 0;
  z-index: 1000;
}

.reading-tools {
  background: white;
  padding: 10px;
  border-bottom: 1px solid #eee;
}

.tool-btn {
  border: none;
  background: none;
  color: #666;
  padding: 5px 15px;
  font-size: 0.9rem;
  cursor: pointer;
}

.tool-btn.active {
  color: #40e0d0;
  font-weight: bold;
}

.reading-content {
  background: white;
  padding: 20px;
  line-height: 1.8;
}

.paragraph {
  margin-bottom: 20px;
  position: relative;
}

.paragraph-number {
  position: absolute;
  left: -25px;
  color: #999;
  font-size: 0.8rem;
}

.question-section {
  margin-top: 15px;
  padding: 20px;
}

.question {
  margin-bottom: 25px;
}


.bottom-tools {
  position: fixed;
  bottom: 0;
  width: 100%;
  background: white;
  padding: 10px 20px;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.translation-panel {
  display: none;
  background: white;
  padding: 15px;
  margin-top: 10px;
  border-radius: 8px;
  color: #666;
}

.chinese-text {
  display: none;
  color: #666;
  background: #f8f9fa;
  padding: 10px 15px;
  margin-top: 10px;
  border-left: 3px solid #40e0d0;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.chinese-text.show {
  display: block;
  opacity: 1;
}

/* 长难句相关样式 */
.difficult-sentence {
  cursor: pointer;
  transition: background-color 0.3s ease;
  display: inline-block;
}

.difficult-sentence.highlight {
  background-color: rgba(64, 224, 208, 0.1);
  border-radius: 4px;
  padding: 2px 4px;
}

.sentence-analysis {
  display: none;
  background: #f8f9fa;
  padding: 15px;
  margin: 10px 0;
  border-radius: 8px;
  border-left: 3px solid #40e0d0;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.sentence-analysis.show {
  display: block;
  opacity: 1;
}

.analysis-title {
  color: #40e0d0;
  font-weight: bold;
  margin-bottom: 10px;
}

.structure-analysis {
  margin: 10px 0;
  padding: 10px;
  background: #fff;
  border-radius: 6px;
}

.translation-result {
  margin-top: 10px;
  padding-top: 10px;
  border-top: 1px dashed #ddd;
}

/* 生词相关样式 */
.new-word {
  cursor: pointer;
  transition: all 0.3s ease;
}

.new-word.highlight {
  background-color: #FFE4B5;
  border-radius: 3px;
  padding: 0 2px;
}

.word-tooltip {
  position: absolute;
  background: white;
  border: 1px solid #ddd;
  border-radius: 6px;
  padding: 10px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  max-width: 300px;
  z-index: 1000;
  display: none;
}

.word-tooltip.show {
  display: block;
}

.word-phonetic {
  color: #666;
  font-size: 0.9em;
  margin-bottom: 5px;
}

.word-meaning {
  border-top: 1px solid #eee;
  padding-top: 5px;
  margin-top: 5px;
}

.word-type {
  color: #40e0d0;
  font-weight: bold;
  margin-right: 5px;
}

/* 单词点击相关样式 */
.word-clickable {
  cursor: pointer;
  padding: 0 2px;
  border-radius: 3px;
  transition: background-color 0.2s;
}

.word-clickable:hover {
  background-color: rgba(64, 224, 208, 0.1);
}

.word-clickable.highlighted {
  background-color: rgba(64, 224, 208, 0.2);
}

.tooltip-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.collect-word-btn {
  background: #40e0d0;
  color: white;
  border: none;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 0.9em;
  cursor: pointer;
}

.collect-word-btn:hover {
  background: #3bcdc0;
}

.collect-word-btn.collected {
  background: #999;
}

.loading-phonetic,
.loading-meaning {
  color: #999;
  font-style: italic;
  font-size: 0.9em;
}

.english-text {
  cursor: default;
  user-select: text;
  line-height: 1.8;
}

/* 让所有英文单词可点击 */
.english-text span,
.english-text {
  cursor: pointer;
}

.english-text span:hover,
.english-text:hover {
  background-color: transparent;
}

/* 添加新的单词样式 */
.clickable-word {
  cursor: pointer;
  padding: 0 1px;
  border-radius: 2px;
  transition: all 0.2s ease;
}

.clickable-word:hover {
  background-color: rgba(64, 224, 208, 0.1);
}

/* 确保新单词和预设生词样式一致 */
.new-word,
.clickable-word {
  display: inline-block;
}

.new-word.highlight {
  background-color: #FFE4B5;
  border-radius: 3px;
  padding: 0 2px;
}

/* 修改长难句相关样式 */
.difficult-sentence {
  cursor: pointer;
  transition: background-color 0.3s ease;
  display: inline-block; /* 确保长难句可以正确显示 */
}

.difficult-sentence.highlight {
  background-color: rgba(64, 224, 208, 0.1);
  border-radius: 4px;
  padding: 2px 4px;
}

/* 确保长难句内的单词不会被分开点击 */
.difficult-sentence .clickable-word {
  cursor: inherit;
  padding: 0;
  border-radius: 0;
  transition: none;
}

.difficult-sentence .clickable-word:hover {
  background-color: transparent;
}
.analysis-loading {
  text-align: center;
  padding: 20px;
  color: #666;
}

.analysis-error {
  text-align: center;
  padding: 20px;
  color: #ff4444;
}

.structure-analysis p {
  margin: 8px 0;
}

.structure-analysis ul {
  margin: 8px 0;
  padding-left: 20px;
  list-style-type: disc;
}

.structure-analysis li {
  margin: 4px 0;
  color: #666;
}

.translation-result p {
  margin: 8px 0;
  line-height: 1.6;
}

.translation-result p strong {
  color: #40e0d0;
}

.analysis-section {
  margin: 15px 0;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 6px;
}

.analysis-section strong {
  color: #40e0d0;
  font-size: 1.1em;
}

.analysis-value {
  margin-top: 10px;
  font-family: monospace;
  font-size: 14px;
  line-height: 1.5;
}

.json-item {
  margin: 4px 0;
  padding-left: 16px;
}

.json-key {
  color: #0066cc;
  font-weight: 500;
}

.json-value {
  margin-left: 8px;
}

.json-array {
  margin-left: 16px;
}

.json-array-item {
  margin: 4px 0;
  padding-left: 8px;
  border-left: 2px solid #eee;
}

.json-primitive {
  color: #444;
}
</style>